class SessionsController < ApplicationController
  prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
  include Devise::Controllers::InternalHelpers

  # GET /resource/sign_in
  def new
    unless resource_just_signed_up?
      Devise::FLASH_MESSAGES.each do |message|
        set_now_flash_message :alert, message if params.try(:[], message) == "true"
      end
    end

    build_resource
    render_with_scope :new
  end

  # POST /resource/sign_in
  def create
    if resource = authenticate(resource_name)
      #set_flash_message :notice, :signed_in


      #pragmatic: se chequea si el usuario tiene definido algun perfil. De no se asi se le avisa
      user = resource
      route = ""
      if !current_user.contact.nil? && !current_user.contact.language.nil?
        I18n.locale = current_user.contact.language
      end

      if I18n.locale == 'en'
        route += Setting.english_website_url
      else
        route += Setting.spanish_website_url
      end

      route += session[:"#{resource_name}.return_to"] unless session[:"#{resource_name}.return_to"].nil?
      if !session[:last_url_without_session].nil? && session[:"#{resource_name}.return_to"].nil?
        puts "session[:last_url_without_session]: #{session[:last_url_without_session]}"
        if session[:last_url_without_session] == "/catalogs"
          route += '/catalogs/index_without_clean'
        else
          route += session[:last_url_without_session]
        end
      end

      session[:"#{resource_name}.return_to"] =  route
      session[:last_url_without_session] = nil

      contact = Contact.find_by_user_id(user.id)
      if !user.role?(:role_admin) && !contact.nil? && (contact.profiles.nil? || contact.profiles.length == 0)
        flash_message :notice, "#{t('contact_profiles.not_contact_profiles')} <a href='#{contact_profiles_path}'>#{t('lbl_define_here')}</a>"
      else
        flash_message :notice, t('devise.sessions.signed_in')
      end



      sign_in_and_redirect(resource_name, resource, true)
    elsif [:custom, :redirect].include?(warden.result)
      throw :warden, :scope => resource_name
    else
      set_now_flash_message :alert, (warden.message || :invalid)
      clean_up_passwords(build_resource)
      render_with_scope :new
    end
  end

  # GET /resource/sign_out
  def destroy
    set_flash_message :notice, :signed_out if signed_in?(resource_name)
    sign_out_and_redirect(resource_name)
  end

  protected

    def resource_just_signed_up?
      flash[:"#{resource_name}_signed_up"]
    end

    def clean_up_passwords(object)
      object.clean_up_passwords if object.respond_to?(:clean_up_passwords)
    end
end
